﻿
//***********************************************************************
// * Module:   TbBstLostmanHandler
// * 作者:  曹荣芝
// * Modified: 2013/5/7
// * Purpose: Definition of the Class TbBstLostmanHandler 业务逻辑处理Handler类
// ***********************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using XWG.Framework.MSException;
using XWG.Framework.AuthUtility;
using XWG.Framework.AuthEntity;
using XWG.Framework.AuthSPConst;
using XWG.Framework.AuthBLL;
using XWG.JWBST.JWBSTEntity;
using XWG.JWBST.JWBSTSPConst;
using System.Web.Script.Serialization;
using System.Data;
using XWG.Framework.Query;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using XWG.JWBST.JWBSTBLL;
using System.IO;
using JWBSTAPP.CommonClass;
using XWG.Framework;
using System.Collections;
namespace JWBSTAPP.AjaxServer
{
    /// <summary>
    /// TbBstLostmanHandler 的摘要说明
    /// </summary>
    public class TbBstLostmanHandler : JWBSTAPP.CommonClass.HttpHandlerBase, System.Web.SessionState.IRequiresSessionState
    {

        #region 添加记录
        /// <summary>
        /// 添加记录
        /// </summary>
        protected void AddRecord()
        {
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            ResultModel mResultModel = new ResultModel(); //初始化返回类型
            try
            {
                TbBstLostman mTbBstLostman = new TbBstLostman();
                var id = Guid.NewGuid().ToString(); //主键
                mTbBstLostman.Id = id;
                mTbBstLostman.Name = DES.Encode(context.Request.Form["texName"]); //走失人姓名
                mTbBstLostman.Gender = context.Request.Form["selGender"]; //性别
                if (!string.IsNullOrEmpty(context.Request.Form["texBirth"]))
                {
                    mTbBstLostman.Birth = DateTime.Parse(context.Request.Form["texBirth"]); //出生日期
                }
                mTbBstLostman.Idcard = DES.Encode(context.Request.Form["texIdcard"]); //身份证
                mTbBstLostman.Note = context.Request.Form["texNote"]; //走失经过描述
                mTbBstLostman.Issuename = DES.Encode(context.Request.Form["texIssuename"]); //发布人姓名
                mTbBstLostman.Issuenphone = DES.Encode(context.Request.Form["texIssuenphone"]); //发布人手机
                mTbBstLostman.Issueidcard = DES.Encode(context.Request.Form["texIssueidcard"]); //发布人身份证号
                mTbBstLostman.Issueaddress = DES.Encode(context.Request.Form["texIssueaddress"]); //发布人地址
                mTbBstLostman.Createdate = DateTime.Now; //修改时间
                mTbBstLostman.Deltag = 0; //删除标志
                //mTbBstLostman.Pic = context.Request.Form["texPic"]; //照片

                #region 图片上传方法
                HttpFileCollection files = context.Request.Files;
                if (files.Count > 0)
                {
                    Random rnd = new Random();
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFile file = files[i];
                        var len = file.ContentLength;
                        if (len > 0)
                        {
                            string fileName = file.FileName;
                            string extension = Path.GetExtension(fileName);
                            if (extension.ToLower() == ".jpg" || extension.ToLower() == ".bmp" || extension.ToLower() == ".gif" || extension.ToLower() == ".png")
                            {
                                string PhotoMaxSize = System.Configuration.ConfigurationManager.AppSettings["PhotoMaxSize"];
                                if (len > int.Parse(PhotoMaxSize) * 1024)
                                {
                                    continue;
                                }


                                var FileDown = id + extension;
                                var Folder = System.DateTime.Now.ToString("yyyyMM");
                                if (System.IO.Directory.Exists(System.Web.HttpContext.Current.Request.MapPath("../../Upload/Photo/" + Folder)) == false)//如果不存在就创建file文件夹
                                {
                                    System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Request.MapPath("../../Upload/Photo/" + Folder));
                                }
                                //保存文件
                                var SaveImgPath = System.Web.HttpContext.Current.Request.MapPath("../../Upload/Photo/" + Folder + "/") + FileDown;
                                Common.MakeThumNail(System.Drawing.Image.FromStream(file.InputStream), SaveImgPath, 90, 120, "HW"); ; //照片
                                mTbBstLostman.Pic = "/Upload/Photo/" + Folder + "/" + FileDown; //照片                                
                            }
                            //int num = rnd.Next(5000, 10000);
                            //string path = "file/" + num.ToString() + extension;
                            //file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path));
                        }
                    }
                }
                #endregion
                mResultModel = TbBstLostmanBLL.Insert(mTbBstLostman, context.Session["UserID"], true); //新建操作
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, "");
                mResultModel.ErrorCode = -9999;
                mResultModel.ISSucceed = false;
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
        }
        #endregion

        #region 删除记录
        /// <summary>
        /// 删除记录
        /// </summary>
        protected void DeleteRecord()
        {

            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            ResultModel mResultModel = new ResultModel(); //声明返回类型
            try
            {
                string[] arryParamKey = context.Request.Params["id"].ToString().Split(',');
                if (arryParamKey.Length == 0)
                {
                    mResultModel.ErrorCode = -9991;
                    mResultModel.ISSucceed = false;
                    context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回    
                    return;
                }
                TbBstLostman mTbBstLostman = new TbBstLostman();
                foreach (var paramKey in arryParamKey)
                {
                    mResultModel = TbBstLostmanBLL.Delete(paramKey, context.Session["UserID"], true); //删除对应的信息
                }
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); ; //序列化后返回
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, ""); //写入异常日志
                mResultModel.ErrorCode = -9999; //-9999代码是系统异常通用代码
                mResultModel.ISSucceed = false; //行为执行失败
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }

        }
        #endregion


        #region 修改记录
        /// <summary>
        /// 修改记录
        /// </summary>
        protected void EditRecord()
        {
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            ResultModel mResultModel = new ResultModel(); //初始化返回类型
            TbBstLostman mTbBstLostman = new TbBstLostman();

            string paramKey = context.Request.Params["id"];
            var id = paramKey;
            try
            {

                if (string.IsNullOrEmpty(paramKey))
                {
                    mResultModel.ErrorCode = -9991;
                    mResultModel.ISSucceed = false;
                    context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回    
                    return;
                }
                mTbBstLostman = TbBstLostmanBLL.Load(paramKey); //根据键值获取实体信息
                if (mTbBstLostman != null)
                {
                    mTbBstLostman.Name = DES.Encode(context.Request.Form["texName"]); //走失人姓名
                    mTbBstLostman.Gender = context.Request.Form["selGender"]; //性别
                    if (!string.IsNullOrEmpty(context.Request.Form["texBirth"]))
                    {
                        mTbBstLostman.Birth = DateTime.Parse(context.Request.Form["texBirth"]); //出生日期
                    }
                    mTbBstLostman.Time = DateTime.Parse(context.Request.Form["texTime"]); //走失时间
                    mTbBstLostman.Idcard = DES.Encode(context.Request.Form["texIdcard"]); //身份证
                    mTbBstLostman.Note = DES.Encode(context.Request.Form["texNote"]); //走失经过描述
                    mTbBstLostman.Issuename = DES.Encode(context.Request.Form["texIssuename"]); //发布人姓名
                    mTbBstLostman.Issuenphone = DES.Encode(context.Request.Form["texIssuenphone"]); //发布人手机
                    mTbBstLostman.Issueidcard = DES.Encode(context.Request.Form["texIssueidcard"]); //发布人身份证号
                    mTbBstLostman.Issueaddress = DES.Encode(context.Request.Form["texIssueaddress"]); //发布人地址
                    mTbBstLostman.Modifydate = DateTime.Now; //修改时间
                    // mTbBstLostman.Pic = context.Request.Form["texPic"]; //照片
                    #region 图片上传方法
                    HttpFileCollection files = context.Request.Files;
                    if (files.Count > 0)
                    {
                        Random rnd = new Random();
                        for (int i = 0; i < files.Count; i++)
                        {
                            HttpPostedFile file = files[i];
                            var len = file.ContentLength;
                            if (len > 0)
                            {
                                string fileName = file.FileName;
                                string extension = Path.GetExtension(fileName);
                                if (extension.ToLower() == ".jpg" || extension.ToLower() == ".bmp" || extension.ToLower() == ".gif" || extension.ToLower() == ".png")
                                {
                                    string PhotoMaxSize = System.Configuration.ConfigurationManager.AppSettings["PhotoMaxSize"];
                                    if (len > int.Parse(PhotoMaxSize) * 1024)
                                    {
                                        continue;
                                    }


                                    var FileDown = id + extension;
                                    var Folder = System.DateTime.Now.ToString("yyyyMM");
                                    if (System.IO.Directory.Exists(System.Web.HttpContext.Current.Request.MapPath("../../Upload/Photo/" + Folder)) == false)//如果不存在就创建file文件夹
                                    {
                                        System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Request.MapPath("../../Upload/Photo/" + Folder));
                                    }
                                    //保存文件
                                    var SaveImgPath = System.Web.HttpContext.Current.Request.MapPath("../../Upload/Photo/" + Folder + "/") + FileDown;
                                    Common.MakeThumNail(System.Drawing.Image.FromStream(file.InputStream), SaveImgPath, 90, 120, "HW"); ; //照片
                                    mTbBstLostman.Pic = "/Upload/Photo/" + Folder + "/" + FileDown; //照片                                
                                }
                                //int num = rnd.Next(5000, 10000);
                                //string path = "file/" + num.ToString() + extension;
                                //file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path));
                            }
                        }
                    }
                    #endregion
                    mResultModel = TbBstLostmanBLL.Update(mTbBstLostman, context.Session["UserID"], true); //新建操作
                }
                else
                {
                    mResultModel.ErrorCode = -9990; //没有获取所需的信息，信息可能已被删除
                    mResultModel.ISSucceed = false;

                }
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, "");
                mResultModel.ErrorCode = -9999;
                mResultModel.ISSucceed = false;
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
        }
        #endregion

        #region 获取实体记录
        /// <summary>
        /// 获取实体记录
        /// </summary>
        protected void GetModel()
        {
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            ResultModel mResultModel = new ResultModel(); //初始化返回类型
            string paramKey = context.Request.Params["id"];
            string json = "";
            try
            {
                TbBstLostman mTbBstLostman = new TbBstLostman(); //声明实体
                TbBstDic mTbBstDic = new TbBstDic();
                if (!string.IsNullOrEmpty(paramKey))
                {
                    mTbBstLostman = TbBstLostmanBLL.Load(paramKey); //根据键值获取管理员
                    if (mTbBstLostman != null)
                    {
                        ////出生日期
                        if (mTbBstLostman.Birth.ToString("yyyy") == "0001")
                        {
                            mTbBstLostman.Birthstr = "暂无修改";
                        }
                        else
                        {
                            mTbBstLostman.Birthstr = mTbBstLostman.Birth.ToString("yyyy-MM-dd HH:mm:ss");
                        }
                        ////修改时间
                        if (mTbBstLostman.Modifydate.ToString("yyyy") == "0001")
                        {
                            mTbBstLostman.Modifydatestr = "暂无修改";
                        }
                        else
                        {
                            mTbBstLostman.Modifydatestr = mTbBstLostman.Modifydate.ToString("yyyy-MM-dd HH:mm:ss");
                        }
                        ////相关字段解密
                        mTbBstLostman.Name = DES.Decode(mTbBstLostman.Name.ToString());
                        mTbBstLostman.Idcard = DES.Decode(mTbBstLostman.Idcard.ToString());
                        mTbBstLostman.Note = mTbBstLostman.Note.ToString();
                        mTbBstLostman.Issuename = DES.Decode(mTbBstLostman.Issuename);
                        mTbBstLostman.Issuenphone = DES.Decode(mTbBstLostman.Issuenphone);
                        mTbBstLostman.Issueidcard = DES.Decode(mTbBstLostman.Issueidcard);
                        mTbBstLostman.Issueaddress = DES.Decode(mTbBstLostman.Issueaddress);
                        IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
                        json = JsonConvert.SerializeObject(mTbBstLostman, dtConverter);
                        //解析性别
                        if (!String.IsNullOrEmpty(mTbBstLostman.Gender))
                        {
                            var list = TbBstDicBLL.GetDicByCodeAndParentnode(mTbBstLostman.Gender, "gender");
                            mTbBstDic = list.FirstOrDefault();
                            Hashtable hashtable = new Hashtable();
                            if (mTbBstDic != null)
                            {
                                hashtable.Add("VGender", mTbBstDic.Description);//VGender为详细页显示的字段名
                                json = JsonString.AddAttribute(json, hashtable);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, "");
                mResultModel.ErrorCode = -9990;
                mResultModel.ISSucceed = false;
                json = JsonConvert.SerializeObject(mResultModel);
            }
            context.Response.Write(json);
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取数据记录
        /// </summary>
        protected void QueryRecord()
        {
            TableMessage tm = new TableMessage();
            HearderMessage hm = new HearderMessage();
            List<HearderMessage> list = new List<HearderMessage>();
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            string pageSize = context.Request.Form["pageSize"];
            string pageIndex = context.Request.Form["pageIndex"];
            string lostName = DES.Encode(context.Request.Form["TexLostName"]);////走失人姓名
            string issueName = DES.Encode(context.Request.Form["texIssueName"]);////找寻人姓名
            string phone = DES.Encode(context.Request.Form["texPhone"]);////找寻人手机
            string timeStart = context.Request.Form["texTimeStart"]; ////添加时间-开始
            string timeEnd = context.Request.Form["texTimeEnd"]; ////添加时间-结束
            if (String.IsNullOrEmpty(pageSize) || String.IsNullOrEmpty(pageIndex) || !AnyString.IsNumeric(pageSize) || !AnyString.IsNumeric(pageIndex))
                return;
            DataTable dtTbBstLostman = new DataTable();
            int intPageSize = Convert.ToInt32(pageSize);
            int intPageIndex = Convert.ToInt32(pageIndex);
            QueryByPage Q = new QueryByPage();
            SqlConditionList sqllist = new SqlConditionList();
            string sqlWhere = " deltag=0 ";
            if (!string.IsNullOrEmpty(lostName)) ////走失人姓名
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.LIKE, TbBstLostmanConst.Columns.Name, '%' + lostName + '%'), SqlLogicOper.AND_LOGIC);
            }
            if (!string.IsNullOrEmpty(issueName)) ////找寻人姓名
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.LIKE, TbBstLostmanConst.Columns.Issuename, '%' + issueName + '%'), SqlLogicOper.AND_LOGIC);
            }
            if (!string.IsNullOrEmpty(phone)) ////找寻人手机号
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.LIKE, TbBstLostmanConst.Columns.Issuenphone, '%' + phone + '%'), SqlLogicOper.AND_LOGIC);
            }

            if (!string.IsNullOrEmpty(timeStart)) ////添加时间-开始
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.NOT_LESS_THAN, TbBstLostmanConst.Columns.Createdate, Convert.ToDateTime(timeStart)), SqlLogicOper.AND_LOGIC);
            }
            if (!string.IsNullOrEmpty(timeEnd)) ////添加时间-结束
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.NOT_MORE_THAN, TbBstLostmanConst.Columns.Createdate, Convert.ToDateTime(timeEnd)), SqlLogicOper.AND_LOGIC);
            }

            if (string.IsNullOrEmpty(sqllist.ToSql()))
            {
                sqlWhere = "where" + sqlWhere;
            }
            else
            {
                sqlWhere = sqllist.ToSql() + " and " + sqlWhere;
            }
            dtTbBstLostman = Q.GetRecordByPage("ID,NAME,ISSUENAME,ISSUENPHONE,CREATEDATE", sqlWhere, " createdate ", intPageSize, intPageIndex, TbBstLostmanConst.TableName, TbBstLostmanConst.FieldKey, "desc").Tables[0];
            if (dtTbBstLostman != null && dtTbBstLostman.Rows.Count > 0)
            {
                for (int i = 0; i < dtTbBstLostman.Columns.Count; i++)
                {
                    hm = new HearderMessage();
                    hm.name = dtTbBstLostman.Columns[i].Caption;
                    list.Add(hm);
                }
                tm.Header = list;
                tm.data = dtTbBstLostman;
                tm.totalCount = Convert.ToString((int)Q.RowCount);
            }
            ////解密相关字段
            for (int j = 0; j < dtTbBstLostman.Rows.Count; j++)
            {
                for (int m = 1; m < 4; m++)
                {
                    string decode = dtTbBstLostman.Rows[j][m].ToString();
                    dtTbBstLostman.Rows[j][m] = DES.Decode(decode);
                }
            }
            IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            string json = JsonConvert.SerializeObject(tm, dtConverter);
            context.Response.Write(json);
        }
        #endregion

    }
}


